package com.example.demo.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

@Component
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DateSourceAspect {
    //读库数据源key
    private static final String DATASOURCE_KEY_READ = "read";
    //查询方法清单
    String[] queryMethods = {"find", "get", "query", "count", "select"};

    @Before("execution(* com.example.demo.mapper..*.*(..))")
    public void before(JoinPoint point){
        String methodName = point.getSignature().getName();
        for (String queryName:queryMethods) {
            if (methodName.startsWith(queryName)) {
                DynamicHolder.setDataSource(DATASOURCE_KEY_READ);
                System.out.print("设置数据库为读");
                break;
            }
        }
    }

    @After("execution(* com.example.demo.mapper..*.*(..))")
    public void after(JoinPoint point){
        DynamicHolder.clearDataSource();
    }

}
